import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'
import FileInput from './FileInput'
import Table from './Table'
import NavLink from './NavLink'
import ImageWithState from './ImageWithState'
import style2 from './addStore.css'
import style from './MallIndex.css'
import { myAjax ,ROOTURL,ROOTURL_MALL} from '../publicAPI/publicAPI'

class MallIndex extends Component {
	 constructor (props, context) {
	      super(props, context);
	      console.log("初始化");
	      this.state = {
	        previewImgFiles: [],
	            previewImgUrl: [],
	            hasBeenMounted: false,
	            shopimg:[],
	            delete : false,
	            deleteId:-1,
	            };
	       this.handleImgUpload.bind(this);
	       this.handlesave.bind(this);

	       this.getlist.bind(this);
	        // 初始化状态
	  }

	  componentWillMount() {
	    this.getlist();

	  }
	  componentDidMount() {
	      console.log("安装成功")
	  	//1

	  }

	  getlist(){

	    var _this=this;
	    _this.state.hashed=[];
	    console.log("清空当前状态");
	      console.log("将安装", this.props.params.id);

	      var Geturl=ROOTURL_MALL+'kabuy/config/dynamic/public/get.api';
	      var data={
	      k:'shopimg'
	};
	   myAjax(Geturl, "POST",data ,function(data) {
	        console.log(data);
	        var need_hashed=JSON.parse(data.v);


	     _this.setState({
	                 shopimg:need_hashed
	                });
	     console.log("shopimg",_this.state.shopimg)

	        }, function(err) {/*location.href="/"*/})


	}

	    handleImgUpload(files) {
	        var fileUrl = [];
	        var _this = this;

	        files.map(file=> {
	            var freader = new FileReader();
	            freader.readAsDataURL(file);
	            freader.onload = function (e) {
	                fileUrl.push({ src :e.target.result});
	                //因异步操作存在多次渲染，待修改
	                _this.setState(Object.assign({}, this.state, {
	                    previewImgFiles: files,
	                    previewImgUrl: fileUrl
	                }));
	            };

	        });
	    }
	    deleteImg(key) {

	        var newFiles = this.state.shopimg;

	        var index_hashed=this.state.shopimg[key].img;
	        newFiles.splice(key, 1);
	      var delete_url=ROOTURL+'asset/images/delete.api';
	      var delete_data={
	        hashed:index_hashed
	      }
	       myAjax(delete_url, "POST", delete_data, function(data) {

	        }, function(err) {/*location.href="/"*/})
	       var end_data=JSON.stringify(newFiles)
	 var data={
	          k:'shopimg',
	          v:end_data
	        }
	        var Seturl=ROOTURL_MALL+'kabuy/config/dynamic/public/set.api';
	        myAjax(Seturl, "POST", data, function(data) {
	        console.log("这一部",data)
	          if(data.k!=null) {
	           location=location;
	          }
	          else{
	            alert("删除失败");
	          }
	        }, function(err) {/*location.href="/"*/})
	 }
	    tHead() {

	    var data = [
	        {name: "图片"},
	        {name: "链接"},
	        {name: "操作"},
	      ]
	    const _headArr = []
	    const _width = {
	      "0" : "30%",
	      "1" : "50%",
	      "2" : "20%",
	    }
	    _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
	    return _headArr;
	  }
	  //render tbody
	  tBody() {
	    var _this=this;
	    var i;
	    var array=new Array();
	    for(i=0;i<this.state.shopimg.length;i++){
	      if(_this.state.shopimg[i].img!=""){
	            array[i]= (<tr key={i}>
	                <td><img src={ROOTURL+ 'asset/images/get.api?hashed='+_this.state.shopimg[i].img} style={{verticalAlign: 'middle',lineHeight:'132px'}}/></td>
	                <td><input type="text" ref={"img"+i} onChange={this.handlechange.bind(this,i)} className={style["comLineHeight"]} defaultValue={_this.state.shopimg[i].href}/></td>
	                <td><span key={'sp'+i} onClick={this.handleDelete.bind(this,i)}><a>删除</a></span></td>
	                </tr>)
	      }
	      else{


	      }
	    }
	    return array;

	}
	handlechange(i){
	  var _this=this;
	  var shopimg=_this.state.shopimg;

	  _this.state.shopimg[i].href=_this.refs["img"+i].value;
	  _this.setState({
	    shopimg:_this.state.shopimg
	  })
	}

	  handleDelete(i){
	        this.setState({
	            delete: !this.state.delete,
	            deleteId : i
	        })
	    }

	  handleurlsave(){

	    var _this=this;
	    var shopimg=_this.state.shopimg;
	    console.log("url",_this.state.shopimg)
	      var Seturl=ROOTURL_MALL+'kabuy/config/dynamic/public/set.api';
	      var end_data={
	        k:'shopimg',
	        v:JSON.stringify(shopimg)
	      }
	        myAjax(Seturl, "POST", end_data, function(data) {
	       console.log(data)
	          if(data.v!="") {
	            alert("保存成功");
	            this.getlist();
	          }
	        }, function(err) {/*location.href="/"*/})

	  }
	  handlesave(){
	    var _this=this;
	    const imgfile_url=this.state.previewImgUrl;
	    const imgfiles=this.state.previewImgFiles;
	    var j=0;
	    for(var i=0;i<imgfiles.length;i++){
	    var img=new Image();
	    img.src=imgfile_url[i].src;
	    const width=img.width;
	    const height=img.height;
	    console.log(width,height);
	    var fd = new FormData();
	    var  xhr = new XMLHttpRequest();
	      xhr.open("POST", ROOTURL + "asset/images/upload.api?width="+width+"&height="+height+"&noShrink="+true);
	      var f =imgfiles[i];
	      var fd = new FormData();
	      fd.append("file", f);
	      xhr.send(fd);
	      xhr.onload=function(data){
	      console.log(data);
	      var status=data.currentTarget.status;
	      if(status==200){

	                          var imageList = _this.state.previewImgUrl;
	                          var imgData = _this.state.previewImgUrl[j];
	                          imageList[j] = imgData;
	                          imgData.msg = '保存成功';
	                          _this.setState({
	                          previewImgUrl : imageList
	                          });

	        j++;
	        console.log("获取成功");

	        var res=data.currentTarget.response;
	        var res_json=JSON.parse(res);
	        var res_hashed=res_json.hashed;
	        console.log(res_hashed);
	        var message={
	          img:res_hashed,
	          href:""
	        }
	        var save_data=new Array();
	        save_data.push(message);
	        console.log("save_data",save_data)
	        console.log("此时状态",_this.state.shopimg)
	        _this.setState(Object.assign({}, this.state, {
	                  shopimg:_this.state.shopimg.concat(save_data)
	                }));
	        var newstate=JSON.stringify(_this.state.shopimg);
	        console.log("newstate",newstate)
	        var data={
	          k:'shopimg',
	          v:newstate
	        }
	        var Seturl=ROOTURL_MALL+'kabuy/config/dynamic/public/set.api';
	        myAjax(Seturl, "POST", data, function(data) {
	          if(data.status==200) {
	          this.getlist();
	          }
	        }, function(err) {/*location.href="/"*/})
	     console.log("检查此时状态",_this.state.shopimg);
	      }
	      else{
	                var imageList = _this.state.previewImgUrl;
	                var imgData = _this.state.previewImgUrl[j];
	                imageList[j] = imgData;
	                imgData.msg = '保存失败';
	                _this.setState({
	                previewImgUrl : imageList
	                });

	        j++;
	      }
	    }
	  }

		}

	render(){
		return (
			<div className="right-wapper " style={{height:"auto"}}>
			    <div className="rt-wrap">
			        <h2 className="catagory">
			            <Link to={`/MallIndex`}><span className={style2['cata-title-current']}>首页轮播图</span></Link>
			            <Link to={`/MallProductTypeM`}><span className={style2['cata-title']}>商品分类管理</span></Link>
			            <Link to={`/MallProductsM`}><span className={style2['cata-title']}>商品管理</span></Link>
			            <Link to={`/MallOrderM`}><span className={style2['cata-title']}>订单管理</span></Link>
			            <Link to={`/MallStoreM`}><span className={style2['cata-title']}>门店管理</span></Link>
			            <Link to={`/MallMember`}><span className={style2['cata-title']}>门店店员管理</span></Link>
			            <Link to={`/MallStatisticsM`}><span className={style2['cata-title']}>商城统计</span></Link>
			            <Link to={`/MallCoupon`}><span className={style2['cata-title']}>优惠券管理</span></Link>
			        </h2>
</div>
	    	<div className={style["wrap"]} id="tb_img">
	    		<div id="filePicker" className={style["hide"]}></div>
	    		<button id="submit"  className={style.btn_blue} onClick={this.handlesave.bind(this)}>保存</button>
	    		<button id="upload" className={style.btn_blue2}>图片选择上传  <FileInput type="file"
                                                                                        fileClass={style["imgUploader-btn"]}
                                                                                        accept=".jpg,.png,.jpeg,.gif,.bmp"
                                                                                        onChange={(files)=>this.handleImgUpload(files)}/>
                                                                                       </button>

          <span className={style["tips dpib"]} style={{marginLeft:'10px'}}>请选择640*280大小的图片。每次上传和删除图片后，请点击左侧“保存”按钮进行保存</span>
          <h3 className={style["catagory"]} style={{marginTop:'30px'}}><span>上传图片列表</span></h3>
          <div className={style["img_show_div"]}>
          <ul ref="img" id="fileList" className={style["img_list"]} >
            {this.state.previewImgUrl.length > 0 ? this.state.previewImgUrl.map((img, index)=> {

                            return <ImageWithState liClassName={style["img_list_li"]} imgClassName={style["img_list_li_img"]} src={img.src} stateMsg={img.msg} id={index}/>
                        }) : null}
            </ul>
           </div>


        </div>
        <div className={style["wrap"]} id="tb_main">
          <span id="hint"></span>
          <h3 className={style["catagory"]}>
            <span>首页banner图片管理</span>
          </h3>
           <Table tableClass={style["banner-table"]}tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
           <div className={style["url_button"]}>
           <button className={style.btn_blue3} onClick={this.handleurlsave.bind(this)}>保存所有链接</button>
           </div>
          </div>
             { this.state.delete ?
                    <div id={style["msgDialog"]}>
                        <div className={style["msgDialog_div"]}><h3 id={style["msgDialog_title"]}>删除提示？</h3><p id={style["msgDialog_content"]}>
                            确认删除？</p>
                            <div className={style["msgDialog_button"]}>
                                <button id={style["msgDialog_yes"]} onClick={this.deleteImg.bind(this,this.state.deleteId)}>确定</button>
                                <button id={style["msgDialog_no"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                                    取消
                                </button>
                            </div>
                        </div>
                    </div> : null}

			</div>

		)
	}
}


export default MallIndex
